package fem3d;

import java.io.IOException;
import java.util.ArrayList;

import math2.ConstantFunctionRnToR;
import fem2.Block;
import fem2.Constraint;
import fem2.Debugger;
import fem2.DistributedLoad;
import fem2.MaterialModel;
import fem2.Mesh;
import fem2.MeshGenerator;
import fem2.MeshUtilities;
import fem2.Model;
import fem2.Node;
import fem2.analysis.Analysis;
import fem2.analysis.LinearStaticAnalysis;
import fem2.element.StructuralElement;
import fem2.enu.EchoLevelType;
import fem2.enu.State;
import fem2.enu.StressType;
import fem2.material.StVenantKirchhoffMM;
import fem2.pre_and_post.GidMeshGenerator;
import fem2.pre_and_post.GidPostStructural;

/**
 * desmonstrate body load capability
 * 
 * @author hbui
 * 
 */
public class StickWithBall {
	static String projDir = "/home/hbui/kratos_janosch";
	static String projName = "stick-with-ball.gid";
	String fn = projDir + '/' + projName + '/' + "mesh1.msh";

	public Model createModel() {
		MeshGenerator mg = new GidMeshGenerator(fn);
		Mesh mesh = mg.getMesh(3);

		Model m = new Model(mesh);

		mesh.setNumberOfFields(3);

		/*
		 * element creation
		 */
		double E = 206850; // =30*10^6 psi x 6.895*10^3 N/m^2
		double nu = 0.3;
		double t = 1;
		double rho = 7800.0e-9; // =7800 kg/m^3
		State ss = State.THREE_DIMENSIONAL;
		MaterialModel mm = new StVenantKirchhoffMM(E, nu, t, rho, ss);
		for (int i = 0; i < mesh.countBlocks(); i++) {
			StructuralElement e = new StructuralElement(mesh.getBlock(i), mm);
			m.addElement(e);
		}

		// mesh.Print();

		/*
		 * conditions
		 */
		Constraint c1 = new Constraint(false, false, false);
		ArrayList<Node> base = MeshUtilities.seekNodesOnSurface(mesh, 0, 1, 0, 500);
		mesh.setConstraint(c1, base);

		ConstantFunctionRnToR F = new ConstantFunctionRnToR(-9.81e3 * rho);
		for (int i = 0; i < mesh.countBlocks(); i++) {
			Block b = mesh.getBlock(i);
			DistributedLoad f = new DistributedLoad(b, null, null, F);
			m.addLoad(f);
		}

		return m;
	}

	public static void main(String[] args) throws IOException {
		Model m = new StickWithBall().createModel();

		Analysis an = new LinearStaticAnalysis(m);
		// an.getStrategy().setSolverType(SolverType.UMFPACK_SOLVER);
		an.getStrategy().setEchoLevel(EchoLevelType.OUTPUT, EchoLevelType.AUX1);
		an.getModel().setEchoLevel(EchoLevelType.AUX1);
		an.run();

		/*
		 * post process
		 */
		// Mesh mesh = m.getMesh();
		// for (int i = 0; i < mesh.countNodes(); i++) {
		// System.out.println(ArrayFormat.format(mesh.getNode(i).getUHatLocal()));
		// }

		GidPostStructural post = new GidPostStructural(projDir, projName);
		post.clearAllPostFiles();
		post.writeMesh(m, 0);
		post.writeNodalDisplacementResults(m, 0);
		post.writeGaussPointStressResults(m, 0, StressType.CAUCHY_STRESS);

		Debugger.warn("Analysis completed");
	}
}
